home *** CD-ROM | disk | FTP | other *** search
/ Internet Surfer: Getting Started / Internet Surfer - Getting Started (Wayzata Technology)(7231)(1995).bin / pc / textfile / faqs / perl_faq / part2 < prev   
Encoding:
Internet Message Format  |  1995-01-01  |  46.4 KB

  1. Xref: bloom-picayune.mit.edu comp.lang.perl:14079 news.answers:4268
  2. Path: bloom-picayune.mit.edu!enterpoop.mit.edu!usc!cs.utexas.edu!uunet!olivea!pagesat!spssig.spss.com!news.oc.com!convex!tchrist
  3. From: tchrist@convex.COM (Tom Christiansen)
  4. Newsgroups: comp.lang.perl,news.answers
  5. Subject: comp.lang.perl FAQ (part 2 of 2)
  6. Message-ID: <1992Nov30.130440.11167@news.eng.convex.com>
  7. Date: 30 Nov 92 13:04:40 GMT
  8. Expires: Mon, 4 Jan 1993 12:00:00 GMT
  9. References: <1992Nov30.124619.8579@news.eng.convex.com>
  10. Sender: usenet@news.eng.convex.com (news access account)
  11. Reply-To: tchrist@convex.COM (Tom Christiansen)
  12. Followup-To: comp.lang.perl
  13. Organization: Convex Computer Corporation, Colorado Springs, CO
  14. Lines: 1348
  15. Approved: news-answers-request@MIT.Edu
  16. Originator: tchrist@pixel.convex.com
  17. Nntp-Posting-Host: pixel.convex.com
  18. X-Disclaimer: This message was written by a user at CONVEX Computer
  19.               Corp. The opinions expressed are those of the user and
  20.               not necessarily those of CONVEX.
  21.  
  22. Archive-name: perl-faq/part2
  23. Version: $Id: perl-tech,v 1.2 92/11/30 05:22:44 tchrist Exp Locker: tchrist $
  24.  
  25. This posting contains answers to the following techical questions
  26. regarding Perl:
  27.  
  28. 2.1) What are all these $@*%<> signs and how do I know when to use them?
  29. 2.2) Why don't backticks work as they do in shells?  
  30. 2.3) How come Perl operators have different precedence than C operators?
  31. 2.4) How come my converted awk/sed/sh script runs more slowly in Perl?
  32. 2.5) How can I call my system's unique C functions from Perl?
  33. 2.6) Where do I get the include files to do ioctl() or syscall()?
  34. 2.7) Why doesn't "local($foo) = <FILE>;" work right?
  35. 2.8) How can I detect keyboard input without reading it?
  36. 2.9) How can I make an array of arrays or other recursive data types?
  37. 2.10) How can I quote a variable to use in a regexp?
  38. 2.11) Why do setuid Perl scripts complain about kernel problems?
  39. 2.12) How do I open a pipe both to and from a command?
  40. 2.13) How can I change the first N letters of a string?
  41. 2.14) How can I manipulate fixed-record-length files?
  42. 2.15) How can I make a file handle local to a subroutine?
  43. 2.16) How can I extract just the unique elements of an array?
  44. 2.17) How can I call alarm() or usleep() from Perl?
  45. 2.18) How can I test whether an array contains a certain element?
  46. 2.19) How can I do an atexit() or setjmp()/longjmp() in Perl?
  47. 2.20) Why doesn't Perl interpret my octal data octally?
  48. 2.21) How do I sort an associative array by value instead of by key?
  49. 2.22) How can I capture STDERR from an external command?
  50. 2.23) Why doesn't open return an error when a pipe open fails?
  51. 2.24) How can I compare two date strings?
  52. 2.25) What's the fastest way to code up a given task in perl?
  53. 2.26) How can I know how many entries are in an associative array?
  54. 2.27) Why can't my perl program read from STDIN after I gave it ^D (EOF) ?
  55. 2.28) Do I always/never have to quote my strings or use semicolons?
  56. 2.29) How can I translate tildes in a filename?
  57. 2.30) How can I convert my shell script to Perl?
  58. 2.31) What is variable suicide and how can I prevent it?
  59. 2.32) Can I use Perl regular expressions to match balanced text?
  60. 2.33) Can I use Perl to run a telnet or ftp session?
  61. 2.34) What does "Malformed command links" mean?
  62. 2.35) How can I set up a footer format to be used with write()?
  63. 2.36) Why does my Perl program keep growing in size?
  64.  
  65.  
  66. 2.1) What are all these $@*%<> signs and how do I know when to use them?
  67.  
  68.     Those are type specifiers: $ for scalar values, @ for indexed arrays,
  69.     and % for hashed arrays.  The * means all types of that symbol name
  70.     and are sometimes used like pointers; the <> are used for inputting
  71.     a record from a filehandle.  See the question on arrays of arrays
  72.     for more about Perl pointers.
  73.  
  74.     Always make sure to use a $ for single values and @ for multiple ones.
  75.     Thus element 2 of the @foo array is accessed as $foo[2], not @foo[2],
  76.     which is a list of length one (not a scalar), and is a fairly common
  77.     novice mistake.  Sometimes you can get by with @foo[2], but it's
  78.     not really doing what you think it's doing for the reason you think
  79.     it's doing it, which means one of these days, you'll shoot yourself
  80.     in the foot; ponder for a moment what these will really do:
  81.     @foo[0] = `cmd args`;
  82.     @foo[2] = <FILE>;
  83.     Just always say $foo[2] and you'll be happier.
  84.  
  85.     This may seem confusing, but try to think of it this way:  you use the
  86.     character of the type which you *want back*.  You could use @foo[1..3] for
  87.     a slice of three elements of @foo, or even @foo{A,B,C} for a slice of
  88.     of %foo.  This is the same as using ($foo[1], $foo[2], $foo[3]) and
  89.     ($foo{A}, $foo{B}, $foo{C}) respectively.  In fact, you can even use
  90.     lists to subscript arrays and pull out more lists, like @foo[@bar] or
  91.     @foo{@bar}, where @bar is in both cases presumably a list of subscripts.
  92.  
  93.     While there are a few places where you don't actually need these type
  94.     specifiers, except for files, you should always use them.  Note that
  95.     <FILE> is NOT the type specifier for files; it's the equivalent of awk's
  96.     getline function, that is, it reads a line from the handle FILE.  When
  97.     doing open, close, and other operations besides the getline function on
  98.     files, do NOT use the brackets.
  99.  
  100.     Beware of saying:
  101.     $foo = BAR;
  102.     Which wil be interpreted as 
  103.     $foo = 'BAR';
  104.     and not as 
  105.     $foo = <BAR>;
  106.     If you always quote your strings, you'll avoid this trap.
  107.  
  108.     Normally, files are manipulated something like this (with appropriate
  109.     error checking added if it were production code):
  110.  
  111.     open (FILE, ">/tmp/foo.$$");
  112.     print FILE "string\n";
  113.     close FILE;
  114.  
  115.     If instead of a filehandle, you use a normal scalar variable with file
  116.     manipulation functions, this is considered an indirect reference to a
  117.     filehandle.  For example,
  118.  
  119.     $foo = "TEST01";
  120.     open($foo, "file");
  121.  
  122.     After the open, these two while loops are equivalent:
  123.  
  124.     while (<$foo>) {}
  125.     while (<TEST01>) {}
  126.  
  127.     as are these two statements:
  128.     
  129.     close $foo;
  130.     close TEST01;
  131.  
  132.     but NOT to this:
  133.  
  134.     while (<$TEST01>) {} # error
  135.         ^
  136.         ^ note spurious dollar sign
  137.  
  138.     This is another common novice mistake; often it's assumed that
  139.  
  140.     open($foo, "output.$$");
  141.  
  142.     will fill in the value of $foo, which was previously undefined.  
  143.     This just isn't so -- you must set $foo to be the name of a valid
  144.     filehandle before you attempt to open it.
  145.  
  146.  
  147. 2.2) Why don't backticks work as they do in shells?  
  148.  
  149.     Several reason.  One is because backticks do not interpolate within
  150.     double quotes in Perl as they do in shells.  
  151.     
  152.     Let's look at two common mistakes:
  153.  
  154.          $foo = "$bar is `wc $file`";  # WRONG
  155.  
  156.     This should have been:
  157.  
  158.      $foo = "$bar is " . `wc $file`;
  159.  
  160.     But you'll have an extra newline you might not expect.  This
  161.     does not work as expected:
  162.  
  163.       $back = `pwd`; chdir($somewhere); chdir($back); # WRONG
  164.  
  165.     Because backticks do not automatically eat trailing or embedded
  166.     newlines.  The chop() function will remove the last character from
  167.     a string.  This should have been:
  168.  
  169.       chop($back = `pwd`); chdir($somewhere); chdir($back);
  170.  
  171.     You should also be aware that while in the shells, embedding
  172.     single quotes will protect variables, in Perl, you'll need 
  173.     to escape the dollar signs.
  174.  
  175.     Shell: foo=`cmd 'safe $dollar'`
  176.     Perl:  $foo=`cmd 'safe \$dollar'`;
  177.     
  178.  
  179. 2.3) How come Perl operators have different precedence than C operators?
  180.  
  181.     Actually, they don't; all C operators have the same precedence in Perl as
  182.     they do in C.  The problem is with a class of functions called list
  183.     operators, e.g. print, chdir, exec, system, and so on.  These are somewhat
  184.     bizarre in that they have different precedence depending on whether you
  185.     look on the left or right of them.  Basically, they gobble up all things
  186.     on their right.  For example,
  187.  
  188.     unlink $foo, "bar", @names, "others";
  189.  
  190.     will unlink all those file names.  A common mistake is to write:
  191.  
  192.     unlink "a_file" || die "snafu";
  193.  
  194.     The problem is that this gets interpreted as
  195.  
  196.     unlink("a_file" || die "snafu");
  197.  
  198.     To avoid this problem, you can always make them look like function calls
  199.     or use an extra level of parentheses:
  200.  
  201.     (unlink "a_file") || die "snafu";
  202.     unlink("a_file")  || die "snafu";
  203.  
  204.     Sometimes you actually do care about the return value:
  205.  
  206.     unless ($io_ok = print("some", "list")) { } 
  207.  
  208.     Yes, print() return I/O success.  That means
  209.  
  210.     $io_ok = print(2+4) * 5;
  211.  
  212.     returns 5 times whether printing (2+4) succeeded, and 
  213.     print(2+4) * 5;
  214.     returns the same 5*io_success value and tosses it.
  215.  
  216.     See the Perl man page's section on Precedence for more gory details,
  217.     and be sure to use the -w flag to catch things like this.
  218.  
  219.  
  220. 2.4) How come my converted awk/sed/sh script runs more slowly in Perl?
  221.  
  222.     The natural way to program in those languages may not make for the fastest
  223.     Perl code.  Notably, the awk-to-perl translator produces sub-optimal code;
  224.     see the a2p man page for tweaks you can make.
  225.  
  226.     Two of Perl's strongest points are its associative arrays and its regular
  227.     expressions.  They can dramatically speed up your code when applied
  228.     properly.  Recasting your code to use them can help a lot.
  229.  
  230.     How complex are your regexps?  Deeply nested sub-expressions with {n,m} or
  231.     * operators can take a very long time to compute.  Don't use ()'s unless
  232.     you really need them.  Anchor your string to the front if you can.
  233.  
  234.     Something like this:
  235.     next unless /^.*%.*$/; 
  236.     runs more slowly than the equivalent:
  237.     next unless /%/;
  238.  
  239.     Note that this:
  240.     next if /Mon/;
  241.     next if /Tue/;
  242.     next if /Wed/;
  243.     next if /Thu/;
  244.     next if /Fri/;
  245.     runs faster than this:
  246.     next if /Mon/ || /Tue/ || /Wed/ || /Thu/ || /Fri/;
  247.     which in turn runs faster than this:
  248.     next if /Mon|Tue|Wed|Thu|Fri/;
  249.     which runs *much* faster than:
  250.     next if /(Mon|Tue|Wed|Thu|Fri)/;
  251.  
  252.     There's no need to use /^.*foo.*$/ when /foo/ will do.
  253.  
  254.     Remember that a printf costs more than a simple print.
  255.  
  256.     Don't split() every line if you don't have to.
  257.  
  258.     Another thing to look at is your loops.  Are you iterating through 
  259.     indexed arrays rather than just putting everything into a hashed 
  260.     array?  For example,
  261.  
  262.     @list = ('abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stv');
  263.  
  264.     for $i ($[ .. $#list) {
  265.         if ($pattern eq $list[$i]) { $found++; } 
  266.     } 
  267.  
  268.     First of all, it would be faster to use Perl's foreach mechanism
  269.     instead of using subscripts:
  270.  
  271.     foreach $elt (@list) {
  272.         if ($pattern eq $elt) { $found++; } 
  273.     } 
  274.  
  275.     Better yet, this could be sped up dramatically by placing the whole
  276.     thing in an associative array like this:
  277.  
  278.     %list = ('abc', 1, 'def', 1, 'ghi', 1, 'jkl', 1, 
  279.          'mno', 1, 'pqr', 1, 'stv', 1 );
  280.     $found += $list{$pattern};
  281.     
  282.     (but put the %list assignment outside of your input loop.)
  283.  
  284.     You should also look at variables in regular expressions, which is
  285.     expensive.  If the variable to be interpolated doesn't change over the
  286.     life of the process, use the /o modifier to tell Perl to compile the
  287.     regexp only once, like this:
  288.  
  289.     for $i (1..100) {
  290.         if (/$foo/o) {
  291.         &some_func($i);
  292.         } 
  293.     } 
  294.  
  295.     Finally, if you have a bunch of patterns in a list that you'd like to 
  296.     compare against, instead of doing this:
  297.  
  298.     @pats = ('_get.*', 'bogus', '_read', '.*exit', '_write');
  299.     foreach $pat (@pats) {
  300.         if ( $name =~ /^$pat$/ ) {
  301.         &some_func();
  302.         last;
  303.         }
  304.     }
  305.  
  306.     If you build your code and then eval it, it will be much faster.
  307.     For example:
  308.  
  309.     @pats = ('_get.*', 'bogus', '_read', '.*exit', '_write');
  310.     $code = <<EOS
  311.         while (<>) { 
  312.             study;
  313. EOS
  314.     foreach $pat (@pats) {
  315.         $code .= <<EOS
  316.         if ( /^$pat\$/ ) {
  317.             &some_func();
  318.             next;
  319.         }
  320. EOS
  321.     }
  322.     $code .= "}\n";
  323.     print $code if $debugging;
  324.     eval $code;
  325.  
  326.  
  327.  
  328. 2.5) How can I call my system's unique C functions from Perl?
  329.  
  330.     If these are system calls and you have the syscall() function, then
  331.     you're probably in luck -- see the next question.  For arbitrary
  332.     library functions, it's not quite so straight-forward.  While you
  333.     can't have a C main and link in Perl routines, if you're
  334.     determined, you can extend Perl by linking in your own C routines.
  335.     See the usub/ subdirectory in the Perl distribution kit for an example
  336.     of doing this to build a Perl that understands curses functions.  It's
  337.     neither particularly easy nor overly-documented, but it is feasible.
  338.  
  339.  
  340. 2.6) Where do I get the include files to do ioctl() or syscall()?
  341.  
  342.     These are generated from your system's C include files using the h2ph
  343.     script (once called makelib) from the Perl source directory.  This will
  344.     make files containing subroutine definitions, like &SYS_getitimer, which
  345.     you can use as arguments to your function.
  346.  
  347.     You might also look at the h2pl subdirectory in the Perl source for how to
  348.     convert these to forms like $SYS_getitimer; there are both advantages and
  349.     disadvantages to this.  Read the notes in that directory for details.  
  350.    
  351.     In both cases, you may well have to fiddle with it to make these work; it
  352.     depends how funny-looking your system's C include files happen to be.
  353.  
  354.     If you're trying to get at C structures, then you should take a look
  355.     at using c2ph, which uses debugger "stab" entries generated by your
  356.     BSD or GNU C compiler to produce machine-independent perl definitions
  357.     for the data structures.  This allows to you avoid hardcoding
  358.     structure layouts, types, padding, or sizes, greatly enhancing
  359.     portability.  c2ph comes with the perl distribution.  On an SCO
  360.     system, GCC only has COFF debugging support by default, so you'll have
  361.     to build GCC 2.1 with DBX_DEBUGGING_INFO defined, and use -gstabs to
  362.     get c2ph to work there.
  363.  
  364.     See the file /pub/perl/info/ch2ph on convex.com via anon ftp 
  365.     for more traps and tips on this process.
  366.  
  367.  
  368. 2.7) Why doesn't "local($foo) = <FILE>;" work right?
  369.  
  370.     Well, it does.  The thing to remember is that local() provides an array
  371.     context, and that the <FILE> syntax in an array context will read all the
  372.     lines in a file.  To work around this, use:
  373.  
  374.     local($foo);
  375.     $foo = <FILE>;
  376.  
  377.     You can use the scalar() operator to cast the expression into a scalar
  378.     context:
  379.  
  380.     local($foo) = scalar(<FILE>);
  381.  
  382.  
  383. 2.8) How can I detect keyboard input without reading it?
  384.  
  385.     You should check out the Frequently Asked Questions list in
  386.     comp.unix.* for things like this: the answer is essentially the same.
  387.     It's very system dependent.  Here's one solution that works on BSD
  388.     systems:
  389.  
  390.     sub key_ready {
  391.         local($rin, $nfd);
  392.         vec($rin, fileno(STDIN), 1) = 1;
  393.         return $nfd = select($rin,undef,undef,0);
  394.     }
  395.  
  396.     A closely related question is how to input a single character from the
  397.     keyboard.  Again, this is a system dependent operation.  The following 
  398.     code that may or may not help you:
  399.  
  400.     $BSD = -f '/vmunix';
  401.     if ($BSD) {
  402.         system "stty cbreak </dev/tty >/dev/tty 2>&1";
  403.     }
  404.     else {
  405.         system "stty", '-icanon',
  406.         system "stty", 'eol', "\001"; 
  407.     }
  408.  
  409.     $key = getc(STDIN);
  410.  
  411.     if ($BSD) {
  412.         system "stty -cbreak </dev/tty >/dev/tty 2>&1";
  413.     }
  414.     else {
  415.         system "stty", 'icanon';
  416.         system "stty", 'eol', '^@'; # ascii null
  417.     }
  418.     print "\n";
  419.  
  420.     You could also handle the stty operations yourself for speed if you're
  421.     going to be doing a lot of them.  This code works to toggle cbreak
  422.     and echo modes on a BSD system:
  423.  
  424.     sub set_cbreak { # &set_cbreak(1) or &set_cbreak(0)
  425.     local($on) = $_[0];
  426.     local($sgttyb,@ary);
  427.     require 'sys/ioctl.ph';
  428.     $sgttyb_t   = 'C4 S' unless $sgttyb_t;  # c2ph: &sgttyb'typedef()
  429.  
  430.     ioctl(STDIN,&TIOCGETP,$sgttyb) || die "Can't ioctl TIOCGETP: $!";
  431.  
  432.     @ary = unpack($sgttyb_t,$sgttyb);
  433.     if ($on) {
  434.         $ary[4] |= &CBREAK;
  435.         $ary[4] &= ~&ECHO;
  436.     } else {
  437.         $ary[4] &= ~&CBREAK;
  438.         $ary[4] |= &ECHO;
  439.     }
  440.     $sgttyb = pack($sgttyb_t,@ary);
  441.  
  442.     ioctl(STDIN,&TIOCSETP,$sgttyb) || die "Can't ioctl TIOCSETP: $!";
  443.     }
  444.  
  445.     Note that this is one of the few times you actually want to use the
  446.     getc() function; it's in general way too expensive to call for normal
  447.     I/O.  Normally, you just use the <FILE> syntax, or perhaps the read()
  448.     or sysread() functions.
  449.  
  450.     For perspectives on more portable solutions, use anon ftp to retrieve
  451.     the file /pub/perl/info/keypress from convex.com.
  452.  
  453.  
  454. 2.9) How can I make an array of arrays or other recursive data types?
  455.  
  456.     Remember that Perl isn't about nested data structures (actually,
  457.     perl0 ..  perl4 weren't, but maybe perl5 will be, at least
  458.     somewhat).  It's about flat ones, so if you're trying to do this, you
  459.     may be going about it the wrong way or using the wrong tools.  You
  460.     might try parallel arrays with common subscripts.
  461.  
  462.     But if you're bound and determined, you can use the multi-dimensional
  463.     array emulation of $a{'x','y','z'}, or you can make an array of names
  464.     of arrays and eval it.
  465.  
  466.     For example, if @name contains a list of names of arrays, you can 
  467.     get at a the j-th element of the i-th array like so:
  468.  
  469.     $ary = $name[$i];
  470.     $val = eval "\$$ary[$j]";
  471.  
  472.     or in one line
  473.  
  474.     $val = eval "\$$name[$i][\$j]";
  475.  
  476.     You could also use the type-globbing syntax to make an array of *name
  477.     values, which will be more efficient than eval.  Here @name hold
  478.     a list of pointers, which we'll have to dereference through a temporary
  479.     variable.
  480.  
  481.     For example:
  482.  
  483.     { local(*ary) = $name[$i]; $val = $ary[$j]; }
  484.  
  485.     In fact, you can use this method to make arbitrarily nested data
  486.     structures.  You really have to want to do this kind of thing
  487.     badly to go this far, however, as it is notationally cumbersome.
  488.  
  489.     Let's assume you just simply *have* to have an array of arrays of
  490.     arrays.  What you do is make an array of pointers to arrays of
  491.     pointers, where pointers are *name values described above.  You
  492.     initialize the outermost array normally, and then you build up your
  493.     pointers from there.  For example:
  494.  
  495.     @w = ( 'ww' .. 'xx' );
  496.     @x = ( 'xx' .. 'yy' );
  497.     @y = ( 'yy' .. 'zz' );
  498.     @z = ( 'zz' .. 'zzz' );
  499.  
  500.     @ww = reverse @w;
  501.     @xx = reverse @x;
  502.     @yy = reverse @y;
  503.     @zz = reverse @z;
  504.  
  505.     Now make a couple of array of pointers to these:
  506.  
  507.     @A = ( *w, *x, *y, *z );
  508.     @B = ( *ww, *xx, *yy, *zz );
  509.  
  510.     And finally make an array of pointers to these arrays:
  511.  
  512.     @AAA = ( *A, *B );
  513.  
  514.     To access an element, such as AAA[i][j][k], you must do this:
  515.  
  516.     local(*foo) = $AAA[$i];
  517.     local(*bar) = $foo[$j];
  518.     $answer = $bar[$k];
  519.  
  520.     Similar manipulations on associative arrays are also feasible.
  521.  
  522.     You could take a look at recurse.pl package posted by Felix Lee
  523.     <flee@cs.psu.edu>, which lets you simulate vectors and tables (lists and
  524.     associative arrays) by using type glob references and some pretty serious
  525.     wizardry.
  526.  
  527.     In C, you're used to creating recursive datatypes for operations
  528.     like recursive decent parsing or tree traversal.  In Perl, these
  529.     algorithms are best implemented using associative arrays.  Take an
  530.     array called %parent, and build up pointers such that $parent{$person}
  531.     is the name of that person's parent.  Make sure you remember that
  532.     $parent{'adam'} is 'adam'. :-) With a little care, this approach can
  533.     be used to implement general graph traversal algorithms as well.
  534.  
  535.  
  536. 2.10) How can I quote a variable to use in a regexp?
  537.  
  538.     From the manual:
  539.  
  540.     $pattern =~ s/(\W)/\\$1/g;
  541.  
  542.     Now you can freely use /$pattern/ without fear of any unexpected
  543.     meta-characters in it throwing off the search.  If you don't know
  544.     whether a pattern is valid or not, enclose it in an eval to avoid
  545.     a fatal run-time error.
  546.  
  547.  
  548. 2.11) Why do setuid Perl scripts complain about kernel problems?
  549.  
  550.     This message:
  551.  
  552.     YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET!
  553.     FIX YOUR KERNEL, PUT A C WRAPPER AROUND THIS SCRIPT, OR USE -u AND UNDUMP!
  554.  
  555.     is triggered because setuid scripts are inherently insecure due to a
  556.     kernel bug.  If your system has fixed this bug, you can compile Perl
  557.     so that it knows this.  Otherwise, create a setuid C program that just
  558.     execs Perl with the full name of the script.  
  559.  
  560.  
  561. 2.12) How do I open a pipe both to and from a command?
  562.  
  563.     In general, this is a dangerous move because you can find yourself in a
  564.     deadlock situation.  It's better to put one end of the pipe to a file.
  565.     For example:
  566.  
  567.     # first write some_cmd's input into a_file, then 
  568.     open(CMD, "some_cmd its_args < a_file |");
  569.     while (<CMD>) {
  570.  
  571.     # or else the other way; run the cmd
  572.     open(CMD, "| some_cmd its_args > a_file");
  573.     while ($condition) {
  574.         print CMD "some output\n";
  575.         # other code deleted
  576.     } 
  577.     close CMD || warn "cmd exited $?";
  578.  
  579.     # now read the file
  580.     open(FILE,"a_file");
  581.     while (<FILE>) {
  582.  
  583.     If you have ptys, you could arrange to run the command on a pty and
  584.     avoid the deadlock problem.  See the chat2.pl package in the
  585.     distributed library for ways to do this.
  586.  
  587.     At the risk of deadlock, it is theoretically possible to use a
  588.     fork, two pipe calls, and an exec to manually set up the two-way
  589.     pipe.  (BSD system may use socketpair() in place of the two pipes,
  590.     but this is not as portable.)  The open2 library function distributed
  591.     with the current perl release will do this for you.
  592.  
  593.     It assumes it's going to talk to something like adb, both writing to
  594.     it and reading from it.  This is presumably safe because you "know"
  595.     that commands like adb will read a line at a time and output a line at
  596.     a time.  Programs like sort that read their entire input stream first,
  597.     however, are quite apt to cause deadlock.
  598.  
  599.  
  600. 2.13) How can I change the first N letters of a string?
  601.  
  602.     Remember that the substr() function produces an lvalue, that is, it may be
  603.     assigned to.  Therefore, to change the first character to an S, you could
  604.     do this:
  605.  
  606.     substr($var,0,1) = 'S';
  607.  
  608.     This assumes that $[ is 0;  for a library routine where you can't know $[,
  609.     you should use this instead:
  610.  
  611.     substr($var,$[,1) = 'S';
  612.  
  613.     While it would be slower, you could in this case use a substitute:
  614.  
  615.     $var =~ s/^./S/;
  616.     
  617.     But this won't work if the string is empty or its first character is a
  618.     newline, which "." will never match.  So you could use this instead:
  619.  
  620.     $var =~ s/^[^\0]?/S/;
  621.  
  622.     To do things like translation of the first part of a string, use substr,
  623.     as in:
  624.  
  625.     substr($var, $[, 10) =~ tr/a-z/A-Z/;
  626.  
  627.     If you don't know then length of what to translate, something like
  628.     this works:
  629.  
  630.     /^(\S+)/ && substr($_,$[,length($1)) =~ tr/a-z/A-Z/;
  631.     
  632.     For some things it's convenient to use the /e switch of the 
  633.     substitute operator:
  634.  
  635.     s/^(\S+)/($tmp = $1) =~ tr#a-z#A-Z#, $tmp/e
  636.  
  637.     although in this case, it runs more slowly than does the previous example.
  638.  
  639.  
  640. 2.14) How can I manipulate fixed-record-length files?
  641.  
  642.     The most efficient way is using pack and unpack.  This is faster than
  643.     using substr.  Here is a sample chunk of code to break up and put back
  644.     together again some fixed-format input lines, in this case, from ps.
  645.  
  646.     # sample input line:
  647.     #   15158 p5  T      0:00 perl /mnt/tchrist/scripts/now-what
  648.     $ps_t = 'A6 A4 A7 A5 A*';
  649.     open(PS, "ps|");
  650.     $_ = <PS>; print;
  651.     while (<PS>) {
  652.         ($pid, $tt, $stat, $time, $command) = unpack($ps_t, $_);
  653.         for $var ('pid', 'tt', 'stat', 'time', 'command' ) {
  654.         print "$var: <", eval "\$$var", ">\n";
  655.         }
  656.         print 'line=', pack($ps_t, $pid, $tt, $stat, $time, $command),  "\n";
  657.     }
  658.  
  659.  
  660. 2.15) How can I make a file handle local to a subroutine?
  661.  
  662.     You must use the type-globbing *VAR notation.  Here is some code to
  663.     cat an include file, calling itself recursively on nested local
  664.     include files (i.e. those with #include "file", not #include <file>):
  665.  
  666.     sub cat_include {
  667.         local($name) = @_;
  668.         local(*FILE);
  669.         local($_);
  670.  
  671.         warn "<INCLUDING $name>\n";
  672.         if (!open (FILE, $name)) {
  673.         warn "can't open $name: $!\n";
  674.         return;
  675.         }
  676.         while (<FILE>) {
  677.         if (/^#\s*include "([^"]*)"/) {
  678.             &cat_include($1);
  679.         } else {
  680.             print;
  681.         }
  682.         }
  683.         close FILE;
  684.     }
  685.  
  686.  
  687. 2.16) How can I extract just the unique elements of an array?
  688.  
  689.     There are several possible ways, depending on whether the
  690.     array is ordered and you wish to preserve the ordering.
  691.  
  692.     a) If @in is sorted, and you want @out to be sorted:
  693.  
  694.     $prev = 'nonesuch';
  695.     @out = grep($_ ne $prev && (($prev) = $_), @in);
  696.  
  697.        This is nice in that it doesn't use much extra memory, 
  698.        simulating uniq's behavior of removing only adjacent
  699.        duplicates.
  700.  
  701.     b) If you don't know whether @in is sorted:
  702.  
  703.     undef %saw;
  704.     @out = grep(!$saw{$_}++, @in);
  705.  
  706.     c) Like (b), but @in contains only small integers:
  707.  
  708.     @out = grep(!$saw[$_]++, @in);
  709.  
  710.     d) A way to do (b) without any loops or greps:
  711.  
  712.     undef %saw;
  713.     @saw{@in} = ();
  714.     @out = sort keys %saw;  # remove sort if undesired
  715.  
  716.     e) Like (d), but @in contains only small positive integers:
  717.  
  718.     undef @ary;
  719.     @ary[@in] = @in;
  720.     @out = sort @ary;
  721.  
  722.  
  723. 2.17) How can I call alarm() or usleep() from Perl?
  724.  
  725.     It's available as a built-in as of version 3.038.  If you want finer
  726.     granularity than 1 second (as usleep() provides) and have itimers and
  727.     syscall() on your system, you can use the following.  You could also
  728.     use select().
  729.  
  730.     It takes a floating-point number representing how long to delay until
  731.     you get the SIGALRM, and returns a floating- point number representing
  732.     how much time was left in the old timer, if any.  Note that the C
  733.     function uses integers, but this one doesn't mind fractional numbers.
  734.  
  735.     # alarm; send me a SIGALRM in this many seconds (fractions ok)
  736.     # tom christiansen <tchrist@convex.com>
  737.     sub alarm {
  738.     require 'syscall.ph';
  739.     require 'sys/time.ph';
  740.  
  741.     local($ticks) = @_;
  742.     local($in_timer,$out_timer);
  743.     local($isecs, $iusecs, $secs, $usecs);
  744.  
  745.     local($itimer_t) = 'L4'; # should be &itimer'typedef()
  746.  
  747.     $secs = int($ticks);
  748.     $usecs = ($ticks - $secs) * 1e6;
  749.  
  750.     $out_timer = pack($itimer_t,0,0,0,0);  
  751.     $in_timer  = pack($itimer_t,0,0,$secs,$usecs);
  752.  
  753.     syscall(&SYS_setitimer, &ITIMER_REAL, $in_timer, $out_timer)
  754.         && die "alarm: setitimer syscall failed: $!";
  755.  
  756.     ($isecs, $iusecs, $secs, $usecs) = unpack($itimer_t,$out_timer);
  757.     return $secs + ($usecs/1e6);
  758.     }
  759.  
  760.  
  761. 2.18) How can I test whether an array contains a certain element?
  762.  
  763.     There are several ways to approach this.  If you are going to make
  764.     this query many times and the values are arbitrary strings, the
  765.     fastest way is probably to invert the original array and keep an
  766.     associative array lying about whose keys are the first array's values.
  767.  
  768.     @blues = ('turquoise', 'teal', 'lapis lazuli');
  769.     undef %is_blue;
  770.     for (@blues) { $is_blue{$_} = 1; }
  771.  
  772.     Now you can check whether $is_blue{$some_color}.  It might have been
  773.     a good idea to keep the blues all in an assoc array in the first place.
  774.  
  775.     If the values are all small integers, you could use a simple
  776.     indexed array.  This kind of an array will take up less space:
  777.  
  778.     @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31);
  779.     undef @is_tiny_prime;
  780.     for (@primes) { $is_tiny_prime[$_] = 1; }
  781.  
  782.     Now you check whether $is_tiny_prime[$some_number].
  783.  
  784.     If the values in question are integers, but instead of strings,
  785.     you can save quite a lot of space by using bit strings instead:
  786.  
  787.     @articles = ( 1..10, 150..2000, 2017 );
  788.     undef $read;
  789.     grep (vec($read,$_,1) = 1, @articles);
  790.     
  791.     Now check whether vec($read,$n,1) is true for some $n.
  792.  
  793.  
  794. 2.19) How can I do an atexit() or setjmp()/longjmp() in Perl?
  795.  
  796.     Perl's exception-handling mechanism is its eval operator.  You 
  797.     can use eval as setjmp and die as longjmp.  Here's an example
  798.     of Larry's for timed-out input, which in C is often implemented
  799.     using setjmp and longjmp:
  800.  
  801.       $SIG{ALRM} = TIMEOUT;
  802.       sub TIMEOUT { die "restart input\n" }
  803.  
  804.       do { eval { &realcode } } while $@ =~ /^restart input/;
  805.  
  806.       sub realcode {
  807.           alarm 15;
  808.           $ans = <STDIN>;
  809.           alarm 0;
  810.       }
  811.  
  812.    Here's an example of Tom's for doing atexit() handling:
  813.  
  814.     sub atexit { push(@_exit_subs, @_) }
  815.  
  816.     sub _cleanup { unlink $tmp }
  817.  
  818.     &atexit('_cleanup');
  819.  
  820.     eval <<'End_Of_Eval';  $here = __LINE__;
  821.     # as much code here as you want
  822.     End_Of_Eval
  823.  
  824.     $oops = $@;  # save error message
  825.  
  826.     # now call his stuff
  827.     for (@_exit_subs) { &$_() }
  828.  
  829.     $oops && ($oops =~ s/\(eval\) line (\d+)/$0 .
  830.         " line " . ($1+$here)/e, die $oops);
  831.  
  832.     You can register your own routines via the &atexit function now.  You
  833.     might also want to use the &realcode method of Larry's rather than
  834.     embedding all your code in the here-is document.  Make sure to leave
  835.     via die rather than exit, or write your own &exit routine and call
  836.     that instead.   In general, it's better for nested routines to exit
  837.     via die rather than exit for just this reason.
  838.  
  839.     Eval is also quite useful for testing for system dependent features,
  840.     like symlinks, or using a user-input regexp that might otherwise
  841.     blowup on you.
  842.  
  843.  
  844. 2.20) Why doesn't Perl interpret my octal data octally?
  845.  
  846.     Perl only understands octal and hex numbers as such when they occur
  847.     as constants in your program.  If they are read in from somewhere
  848.     and assigned, then no automatic conversion takes place.  You must
  849.     explicitly use oct() or hex() if you want this kind of thing to happen.
  850.     Actually, oct() knows to interpret both hex and octal numbers, while
  851.     hex only converts hexadecimal ones.  For example:
  852.  
  853.     {
  854.         print "What mode would you like? ";
  855.         $mode = <STDIN>;
  856.         $mode = oct($mode);
  857.         unless ($mode) {
  858.         print "You can't really want mode 0!\n";
  859.         redo;
  860.         } 
  861.         chmod $mode, $file;
  862.     } 
  863.  
  864.     Without the octal conversion, a requested mode of 755 would turn 
  865.     into 01363, yielding bizarre file permissions of --wxrw--wt.
  866.  
  867.     If you want something that handles decimal, octal and hex input, 
  868.     you could follow the suggestion in the man page and use:
  869.  
  870.     $val = oct($val) if $val =~ /^0/;
  871.  
  872. 2.21) How do I sort an associative array by value instead of by key?
  873.  
  874.     You have to declare a sort subroutine to do this.  Let's assume
  875.     you want an ASCII sort on the values of the associative array %ary.
  876.     You could do so this way:
  877.  
  878.     foreach $key (sort by_value keys %ary) {
  879.         print $key, '=', $ary{$key}, "\n";
  880.     } 
  881.     sub by_value { $ary{$a} cmp $ary{$b}; }
  882.  
  883.     If you wanted a descending numeric sort, you could do this:
  884.  
  885.     sub by_value { $ary{$b} <=> $ary{$a}; }
  886.  
  887.     You can also inline your sort function, like this:
  888.  
  889.     foreach $key ( sort { $ary{$b} <=> $ary{$a} } keys %ary ) {
  890.         print $key, '=', $ary{$key}, "\n";
  891.     } 
  892.  
  893.     If you wanted a function that didn't have the array name hard-wired
  894.     into it, you could so this:
  895.  
  896.     foreach $key (&sort_by_value(*ary)) {
  897.         print $key, '=', $ary{$key}, "\n";
  898.     } 
  899.     sub sort_by_value {
  900.         local(*x) = @_;
  901.         sub _by_value { $x{$a} cmp $x{$b}; } 
  902.         sort _by_value keys %x;
  903.     } 
  904.  
  905.     If you want neither an alphabetic nor a numeric sort, then you'll 
  906.     have to code in your own logic instead of relying on the built-in
  907.     signed comparison operators "cmp" and "<=>".
  908.  
  909.     Note that if you're sorting on just a part of the value, such as a
  910.     piece you might extract via split, unpack, pattern-matching, or
  911.     substr, then rather than performing that operation inside your sort
  912.     routine on each call to it, it is significantly more efficient to
  913.     build a parallel array of just those portions you're sorting on, sort
  914.     the indices of this parallel array, and then to subscript your original
  915.     array using the newly sorted indices.  This method works on both
  916.     regular and associative arrays, since both @ary[@idx] and @ary{@idx}
  917.     make sense.  See page 245 in the Camel Book on "Sorting an Array by a
  918.     Computable Field" for a simple example of this.
  919.  
  920.  
  921. 2.22) How can I capture STDERR from an external command?
  922.  
  923.     There are three basic ways of running external commands:
  924.  
  925.     system $cmd;
  926.     $output = `$cmd`;
  927.     open (PIPE, "cmd |");
  928.  
  929.     In the first case, both STDOUT and STDERR will go the same place as
  930.     the script's versions of these, unless redirected.  You can always put
  931.     them where you want them and then read them back when the system
  932.     returns.  In the second and third cases, you are reading the STDOUT
  933.     *only* of your command.  If you would like to have merged STDOUT and
  934.     STDERR, you can use shell file-descriptor redirection to dup STDERR to
  935.     STDOUT:
  936.  
  937.     $output = `$cmd 2>&1`;
  938.     open (PIPE, "cmd 2>&1 |");
  939.  
  940.     Another possibility is to run STDERR into a file and read the file 
  941.     later, as in 
  942.  
  943.     $output = `$cmd 2>some_file`;
  944.     open (PIPE, "cmd 2>some_file |");
  945.     
  946.     Here's a way to read from both of them and know which descriptor
  947.     you got each line from.  The trick is to pipe only STDERR through
  948.     sed, which then marks each of its lines, and then sends that
  949.     back into a merged STDOUT/STDERR stream, from which your Perl program
  950.     then reads a line at a time:
  951.  
  952.         open (CMD, 
  953.           "3>&1 (cmd args 2>&1 1>&3 3>&- | sed 's/^/STDERR:/' 3>&-) 3>&- |");
  954.  
  955.         while (<CMD>) {
  956.           if (s/^STDERR://)  {
  957.               print "line from stderr: ", $_;
  958.           } else {
  959.               print "line from stdout: ", $_;
  960.           }
  961.         }
  962.  
  963.     Be apprised that you *must* use Bourne shell redirection syntax
  964.     here, not csh!  In fact, you can't even do these things with csh.
  965.     For details on how lucky you are that perl's system() and backtick
  966.     and pipe opens all use Bourne shell, fetch the file from convex.com
  967.     called /pub/csh.whynot -- and you'll be glad that perl's shell
  968.     interface is the Bourne shell.
  969.  
  970.  
  971. 2.23) Why doesn't open return an error when a pipe open fails?
  972.  
  973.     These statements:
  974.  
  975.     open(TOPIPE, "|bogus_command") || die ...
  976.     open(FROMPIPE, "bogus_command|") || die ...
  977.  
  978.     will not fail just for lack of the bogus_command.  They'll only
  979.     fail if the fork to run them fails, which is seldom the problem.
  980.  
  981.     If you're writing to the TOPIPE, you'll get a SIGPIPE if the child
  982.     exits prematurely or doesn't run.  If you are reading from the
  983.     FROMPIPE, you need to check the close() to see what happened.
  984.  
  985.     If you want an answer sooner than pipe buffering might otherwise
  986.     afford you, you can do something like this:
  987.  
  988.     $kid = open (PIPE, "bogus_command |");   # XXX: check defined($kid)
  989.     (kill 0, $kid) || die "bogus_command failed";
  990.  
  991.     This works fine if bogus_command doesn't have shell metas in it, but
  992.     if it does, the shell may well not have exited before the kill 0.  You
  993.     could always introduce a delay:
  994.  
  995.     $kid = open (PIPE, "bogus_command </dev/null |");
  996.     sleep 1;
  997.     (kill 0, $kid) || die "bogus_command failed";
  998.  
  999.     but this is sometimes undesirable, and in any event does not guarantee
  1000.     correct behavior.  But it seems slightly better than nothing.
  1001.  
  1002.     Similar tricks can be played with writable pipes if you don't wish to
  1003.     catch the SIGPIPE.
  1004.  
  1005.  
  1006. 2.24) How can I compare two date strings?
  1007.  
  1008.     If the dates are in an easily parsed, predetermined format, then you
  1009.     can break them up into their component parts and call &timelocal from
  1010.     the distributed perl library.  If the date strings are in arbitrary
  1011.     formats, however, it's probably easier to use the getdate program
  1012.     from the Cnews distribution, since it accepts a wide variety of dates.
  1013.     Note that in either case the return values you will really be
  1014.     comparing will be the total time in seconds as return by time().
  1015.    
  1016.     Here's a getdate function for perl that's not very efficient; you 
  1017.     can do better this by sending it many dates at once or modifying
  1018.     getdate to behave better on a pipe.  Beware the hardcoded pathname.
  1019.  
  1020.     sub getdate {
  1021.         local($_) = shift;
  1022.  
  1023.         s/-(\d{4})$/+$1/ || s/\+(\d{4})$/-$1/; 
  1024.         # getdate has broken timezone sign reversal!
  1025.  
  1026.         $_ = `/usr/local/lib/news/newsbin/getdate '$_'`;
  1027.         chop;
  1028.         $_;
  1029.     } 
  1030.  
  1031.     Richard Ohnemus <rick@IMD.Sterling.COM> actually has a getdate.y
  1032.     for use with the Perl yacc.  You can get this from ftp.sterling.com
  1033.     [192.124.9.1] in /local/perl-byacc1.8.1.tar.Z, or send the author
  1034.     mail for details.
  1035.  
  1036.  
  1037. 2.25) What's the fastest way to code up a given task in perl?
  1038.  
  1039.     Because Perl so lends itself to a variety of different approaches
  1040.     for any given task, a common question is which is the fastest way
  1041.     to code a given task.  Since some approaches can be dramatically
  1042.     more efficient that others, it's sometimes worth knowing which is
  1043.     best.  Unfortunately, the implementation that first comes to mind,
  1044.     perhaps as a direct translation from C or the shell, often yields
  1045.     suboptimal performance.  Not all approaches have the same results
  1046.     across different hardware and software platforms.  Furthermore,
  1047.     legibility must sometimes be sacrificed for speed.
  1048.  
  1049.     While an experienced perl programmer can sometimes eye-ball the code
  1050.     and make an educated guess regarding which way would be fastest,
  1051.     surprises can still occur.  So, in the spirit of perl programming
  1052.     being an empirical science, the best way to find out which of several
  1053.     different methods runs the fastest is simply to code them all up and
  1054.     time them. For example:
  1055.  
  1056.     $COUNT = 10_000; $| = 1;
  1057.  
  1058.     print "method 1: ";
  1059.  
  1060.         ($u, $s) = times;
  1061.         for ($i = 0; $i < $COUNT; $i++) {
  1062.         # code for method 1
  1063.         }
  1064.         ($nu, $ns) = times;
  1065.         printf "%8.4fu %8.4fs\n", ($nu - $u), ($ns - $s);
  1066.  
  1067.     print "method 2: ";
  1068.  
  1069.         ($u, $s) = times;
  1070.         for ($i = 0; $i < $COUNT; $i++) {
  1071.         # code for method 2
  1072.         }
  1073.         ($nu, $ns) = times;
  1074.         printf "%8.4fu %8.4fs\n", ($nu - $u), ($ns - $s);
  1075.  
  1076.     For more specific tips, see the section on Efficiency in the
  1077.     ``Other Oddments'' chapter at the end of the Camel Book.
  1078.  
  1079.  
  1080. 2.26) How can I know how many entries are in an associative array?
  1081.  
  1082.     While the number of elements in a @foobar array is simply @foobar when
  1083.     used in a scalar, you can't figure out how many elements are in an
  1084.     associative array in an analogous fashion.  That's because %foobar in
  1085.     a scalar context returns the ratio (as a string) of number of buckets
  1086.     filled versus the number allocated.  For example, scalar(%ENV) might
  1087.     return "20/32".  While perl could in theory keep a count, this would
  1088.     break down on associative arrays that have been bound to dbm files.
  1089.  
  1090.     However, while you can't get a count this way, one thing you *can* use
  1091.     it for is to determine whether there are any elements whatsoever in
  1092.     the array, since "if (%table)" is guaranteed to be false if nothing
  1093.     has ever been stored in it.  
  1094.  
  1095.     So you either have to keep your own count around and increments
  1096.     it every time you store a new key in the array, or else do it
  1097.     on the fly when you really care, perhaps like this:
  1098.  
  1099.     $count++ while each %ENV;
  1100.  
  1101.     This preceding method will be faster than extracting the
  1102.     keys into a temporary array to count them.
  1103.  
  1104.     As of a very recent patch, you can say
  1105.  
  1106.     $count = keys %ENV;
  1107.  
  1108.  
  1109.  
  1110. 2.27) Why can't my perl program read from STDIN after I gave it ^D (EOF) ?
  1111.  
  1112.     Because some stdio's set error and eof flags that need clearing.
  1113.  
  1114.     Try keeping around the seekpointer and go there, like this:
  1115.      $where = tell(LOG);
  1116.      seek(LOG, $where, 0);
  1117.  
  1118.     If that doesn't work, try seeking to a different part of the file and
  1119.     then back.  If that doesn't work, try seeking to a different part of
  1120.     the file, reading something, and then seeking back.  If that doesn't
  1121.     work, give up on your stdio package and use sysread.  You can't call
  1122.     stdio's clearerr() from Perl, so if you get EINTR from a signal
  1123.     handler, you're out of luck.  Best to just use sysread() from the
  1124.     start for the tty.
  1125.  
  1126.  
  1127. 2.28) Do I always/never have to quote my strings or use semicolons?
  1128.  
  1129.     You don't have to quote strings that can't mean anything else
  1130.     in the language, like identifiers with any upper-case letters
  1131.     in them.  Therefore, it's fine to do this:
  1132.  
  1133.     $SIG{INT} = Timeout_Routine;
  1134.     or 
  1135.  
  1136.     @Days = (Sun, Mon, Tue, Wed, Thu, Fri, Sat, Sun);
  1137.  
  1138.     but you can't get away with this:
  1139.  
  1140.     $foo{while} = until;
  1141.  
  1142.     in place of 
  1143.  
  1144.     $foo{'while'} = 'until';
  1145.  
  1146.     The requirements on semicolons have been increasingly relaxed.  You no
  1147.     longer need one at the end of a block, but stylistically, you're
  1148.     better to use them if you don't put the curly brace on the same line:
  1149.  
  1150.     for (1..10) { print }
  1151.  
  1152.     is ok, as is
  1153.  
  1154.     @nlist = sort { $a <=> $b } @olist;
  1155.  
  1156.     but you probably shouldn't do this:
  1157.     
  1158.     for ($i = 0; $i < @a; $i++) {
  1159.         print "i is $i\n"  # <-- oops!
  1160.     } 
  1161.  
  1162.     because you might want to add lines later, and anyway, 
  1163.     it looks funny. :-)
  1164.  
  1165.  
  1166. 2.29) How can I translate tildes in a filename?
  1167.  
  1168.     Perl doesn't expand tildes -- the shell (ok, some shells) do.
  1169.     The classic request is to be able to do something like:
  1170.  
  1171.     open(FILE, "~/dir1/file1");
  1172.     open(FILE, "~tchrist/dir1/file1");
  1173.  
  1174.     which doesn't work.  (And you don't know it, because you 
  1175.     did a system call without an "|| die" clause! :-)
  1176.  
  1177.     If you *know* you're on a system with the csh, and you *know*
  1178.     that Larry hasn't internalized file globbing, then you could
  1179.     get away with 
  1180.  
  1181.     $filename = <~tchrist/dir1/file1>;
  1182.  
  1183.     but that's pretty iffy.
  1184.  
  1185.     A better way is to do the translation yourself, as in:
  1186.  
  1187.     $filename =~ s#^~(\w+)(/.*)?$#(getpwnam($1))[7].$2#e;
  1188.  
  1189.     More robust and efficient versions that checked for error conditions,
  1190.     handed simple ~/blah notation, and cached lookups are all reasonable
  1191.     enhancements.
  1192.  
  1193.  
  1194. 2.30) How can I convert my shell script to Perl?
  1195.  
  1196.     Larry's standard answer for this is to send your script to me (Tom
  1197.     Christiansen) with appropriate supplications and offerings.  :-(
  1198.     That's because there's no automatic machine translator.  Even if you
  1199.     were, you wouldn't gain a lot, as most of the external programs would
  1200.     still get called.  It's the same problem as blind translation into C:
  1201.     you're still apt to be bogged down by exec()s.  You have to analyze
  1202.     the dataflow and algorithm and rethink it for optimal speedup.  It's
  1203.     not uncommon to see one, two, or even three orders of magnitude of
  1204.     speed difference between the brute-force and the recoded approaches.
  1205.  
  1206.  
  1207. 2.31) What is variable suicide and how can I prevent it?
  1208.  
  1209.     Variable suicide is a nasty sideeffect of dynamic scoping and
  1210.     the way variables are passed by reference.  If you say
  1211.  
  1212.     $x = 17;
  1213.     &munge($x);
  1214.     sub munge {
  1215.         local($x);
  1216.         local($myvar) = $_[0];
  1217.         ...
  1218.     } 
  1219.  
  1220.     Then you have just clubbered $_[0]!  Why this is occurring 
  1221.     is pretty heavy wizardry: the reference to $x stored in 
  1222.     $_[0] was temporarily occluded by the previous local($x)
  1223.     statement (which, you're recall, occurs at run-time, not
  1224.     compile-time).  The work around is simple, however: declare
  1225.     your formal parameters first:
  1226.  
  1227.     sub munge {
  1228.         local($myvar) = $_[0];
  1229.         local($x);
  1230.         ...
  1231.     }
  1232.  
  1233.     That doesn't help you if you're going to be trying to access
  1234.     @_ directly after the local()s.  In this case, careful use
  1235.     of the package facility is your only recourse.
  1236.  
  1237.     Another manifestation of this problem occurs due to the
  1238.     magical nature of the index variable in a foreach() loop.
  1239.  
  1240.     @num = 0 .. 4;
  1241.     print "num begin  @num\n";
  1242.     foreach $m (@num) { &ug }
  1243.     print "num finish @num\n";
  1244.     sub ug {
  1245.         local($m) = 42;
  1246.         print "m=$m  $num[0],$num[1],$num[2],$num[3]\n";
  1247.     }
  1248.     
  1249.     Which prints out the mysterious:
  1250.  
  1251.     num begin  0 1 2 3 4
  1252.     m=42  42,1,2,3
  1253.     m=42  0,42,2,3
  1254.     m=42  0,1,42,3
  1255.     m=42  0,1,2,42
  1256.     m=42  0,1,2,3
  1257.     num finish 0 1 2 3 4
  1258.  
  1259.     What's happening here is that $m is an alias for each 
  1260.     element of @num.  Inside &ug, you temporarily change
  1261.     $m.  Well, that means that you've also temporarily 
  1262.     changed whatever $m is an alias to!!  The only workaround
  1263.     is to be careful with global variables, using packages,
  1264.     and/or just be aware of this potential in foreach() loops.
  1265.  
  1266.  
  1267. 2.32) Can I use Perl regular expressions to match balanced text?
  1268.  
  1269.     No, or at least, not by the themselves.
  1270.  
  1271.     Regexps just aren't powerful enough.  Although Perl's patterns aren't
  1272.     strictly regular because they do backtracking (the \1 notation), you
  1273.     still can't do it.  You need to employ auxiliary logic.  A simple
  1274.     approach would involve keeping a bit of state around, something 
  1275.     vaguely like this (although we don't handle patterns on the same line):
  1276.  
  1277.     while(<>) {
  1278.         if (/pat1/) {
  1279.         if ($inpat++ > 0) { warn "already saw pat1" } 
  1280.         redo;
  1281.         } 
  1282.         if (/pat2/) {
  1283.         if (--$inpat < 0) { warn "never saw pat1" } 
  1284.         redo;
  1285.         } 
  1286.     }
  1287.  
  1288.     A rather more elaborate subroutine to pull out balanced and possibly
  1289.     nested single chars, like ` and ', { and }, or ( and ) can be found
  1290.     on convex.com in /pub/perl/scripts/pull_quotes.
  1291.  
  1292.  
  1293. 2.33) Can I use Perl to run a telnet or ftp session?
  1294.  
  1295.     Sure, you can connect directly to them using sockets, or you can run a
  1296.     session on a pty.  In either case, Randal's chat2 package, which is
  1297.     distributed with the perl source, will come in handly.  It address
  1298.     much the same problem space as Don Libes's expect package does.  Two
  1299.     examples of using managing an ftp session using chat2 can be found on
  1300.     convex.com in /pub/perl/scripts/ftp-chat2.shar .
  1301.  
  1302.     Caveat lector: chat2 is documented only by example, may not run on
  1303.     System V systems, and is subtly machine dependent both in its ideas
  1304.     of networking and in pseudottys.
  1305.  
  1306.  
  1307. 2.34) What does "Malformed command links" mean?
  1308.  
  1309.     This is a bug in 4.035.  While in general it's merely a cosmetic
  1310.     problem, it often comanifests with a highly undesirable coredumping
  1311.     problem.  Programs known to be affected by the fatal coredump include
  1312.     plum and pcops.  Since perl5 is pretty much a total rewrite, we can
  1313.     count on it being fixed then, but if anyone tracks down the coredump
  1314.     problem before then, a significant portion of the Perl world would
  1315.     rejoice.
  1316.  
  1317.  
  1318. 2.35) How can I set up a footer format to be used with write()?
  1319.  
  1320.     While the $^ variable contains the name of the current header format,
  1321.     there is no corresponding mechanism to automatically do the same thing
  1322.     for a footer.  Not knowing how big a format is going to be until you
  1323.     evaluate it is one of the major problems.
  1324.  
  1325.     If you have a fixed-size footer, you can get footers by checking for
  1326.     line left on page ($-) before each write, and printing the footer
  1327.     yourself if necessary.
  1328.  
  1329.     Another strategy is to open a pipe to yourself, using open(KID, "|-")
  1330.     and always write()ing to the KID, who then postprocesses its STDIN to
  1331.     rearrange headers and footers however you like.  Not very convenient,
  1332.     but doable.
  1333.  
  1334.  
  1335. 2.36) Why does my Perl program keep growing in size?
  1336.  
  1337.     While there may be a real memory leak in the Perl source code or even
  1338.     whichever malloc() you're using, common causes are incomplete eval()s
  1339.     or local()s in loops.
  1340.  
  1341.     An eval() which terminates in error due to a failed parsing 
  1342.     will leave a bit of memory unusable.
  1343.  
  1344.     A local() inside a loop:
  1345.  
  1346.     for (1..100) {
  1347.         local(@array);
  1348.     } 
  1349.  
  1350.     will build up 100 versions of @array before the loop is done.
  1351.     The work-around is:
  1352.  
  1353.     local(@array);
  1354.     for (1..100) {
  1355.         undef @array;
  1356.     } 
  1357.  
  1358.     Larry reports that this behavior is fixed for perl5.
  1359.  
  1360. --
  1361.     Tom Christiansen      tchrist@convex.com      convex!tchrist
  1362.  
  1363.     Miksch's Law:
  1364.             If a string has one end, then it has another end.
  1365. -- 
  1366.     Tom Christiansen      tchrist@convex.com      convex!tchrist
  1367.  
  1368.  
  1369. It's all magic.  :-)    --Larry Wall in <7282@jpl-devvax.JPL.NASA.GOV>
  1370.